package com.padgett.resourcemanagement;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.padgett.resourcemanagement.data.ClientDAO;

/**
 * Get Business Client including all services and invoices.
 * 
 * @author andyleung
 * 
 */
@SuppressWarnings("serial")
public class AjaxSaveUserRoleServlet extends HttpServlet{
	private static final Logger logger=Logger.getLogger(AjaxSaveUserRoleServlet.class.getName());
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		String userId=req.getParameter("UserId");
		String role=req.getParameter("Role");
		Key key=new KeyFactory.Builder("User",userId).getKey();
		Entity user=ClientDAO.loadEntity(key);
		user.setProperty("Role", role);
		Key savedUserKey=ClientDAO.saveEntity(user);
		JSONObject response=new JSONObject();
		try {
			if(savedUserKey!=null){
				response.put("success", "true");
				response.put("invoiceId", KeyFactory.keyToString(savedUserKey));
			}else{
				response.put("success", "false");
				response.put("error", "Unable to save user role at the moment.");
			}
		} catch (JSONException e) {
			logger.severe(e.getMessage());
			e.printStackTrace();
		}
		resp.getWriter().write(response.toString());
	}
}
